package cn.schoolwow.flow.monitor.domain.handler;

import cn.schoolwow.flow.monitor.module.initial.flow.InsertFlowLogFlow;
import cn.schoolwow.flow.monitor.module.initial.flow.SetConfigParameterFlow;
import cn.schoolwow.flow.monitor.module.initial.flow.UpdateFlowLogFlow;
import cn.schoolwow.flow.monitor.domain.FlowMonitorOption;
import cn.schoolwow.flow.monitor.entity.FlowLog;
import cn.schoolwow.flow.monitor.entity.ScheduleJobLog;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.listener.TryCatchFinallyHandler;
import cn.schoolwow.util.domain.beanCopy.BeanCopy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class TaskLogTryCatchFinallyHandler implements TryCatchFinallyHandler {
    private Logger logger = LoggerFactory.getLogger(TaskLogTryCatchFinallyHandler.class);

    @Override
    public void handleTryStart(FlowContext flowContext) {
        flowContext.putTemporaryData("是否保存流程日志", false);
        flowContext.executeFlowList(new InsertFlowLogFlow(),new SetConfigParameterFlow());
    }

    @Override
    public void handleTryEnd(FlowContext flowContext) throws Exception {

    }

    @Override
    public void handleException(FlowContext flowContext, Exception e) {
        logger.error(e.getMessage(), e);
    }

    @Override
    public void handleFinally(FlowContext flowContext) {
        ApplicationContext applicationContext = flowContext.checkInstanceData(ApplicationContext.class);
        FlowMonitorOption flowMonitorOption = applicationContext.getBean(FlowMonitorOption.class);

        flowContext.executeFlowList(new UpdateFlowLogFlow());
        FlowLog flowLog = flowContext.checkInstanceData(FlowLog.class);

        ScheduleJobLog scheduleJobLog = BeanCopy.cloneObject(flowLog, ScheduleJobLog.class);
        flowMonitorOption.dao.insert(scheduleJobLog);
    }

    @Override
    public String name() {
        return "定时任务日志记录处理器";
    }
}
